package com.chainyoung.component_tmperson.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.chainyoung.common.appcommon.entity.EthPrice;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.hdwallet.ExchangeCalculator;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;

import com.chainyoung.component_tmperson.di.component.DaggerPersonFragmentComponent;
import com.chainyoung.component_tmperson.di.module.PersonFragmentModule;
import com.chainyoung.component_tmperson.ui.activity.cloudwallet.SelectCoinTypeActivity;
import com.chainyoung.component_tmperson.ui.adapter.LocalWalletListAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletLocalContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletLocalPresenter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_TOTAL_ASSET;
import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_CLOUD;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_LOCAl;


public class WalletLocalListFragment extends BaseFragment<WalletLocalPresenter> implements WalletLocalContract.View {


    @BindView(R2.id.txt_asset_title)
    TextView txtAssetTitle;
    @BindView(R2.id.tv_asset_total)
    TextView tvAssetTotal;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.ll_list)
    RelativeLayout llList;
    @BindView(R2.id.txt_step1)
    TextView txtStep1;
    @BindView(R2.id.txt_step2)
    TextView txtStep2;
    @BindView(R2.id.txt_step3)
    TextView txtStep3;
    @BindView(R2.id.tv_create_wallet)
    TextView tvCreateWallet;
    @BindView(R2.id.ll_guide)
    LinearLayout llGuide;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private boolean isLocalWalletOpened = false;
    private boolean isFistRequest = true;

    //private List<HdWallet> walletList = new ArrayList<>();//以后walletList 也只保证保留每一个币种的一个钱包

    private List<HdWalletCache> hdwallets = new ArrayList<>();

    private LocalWalletListAdapter adapter;

    /**
     * 资产是否可见
     */
    private boolean isVisible = true;


    /**
     * 本地钱包总资产
     */
    private String totalAsset = "0";

    private BigDecimal ethRate = BigDecimal.valueOf(6.8409);//eth 对CNY 汇率


    public static WalletLocalListFragment newInstance(boolean isVisible) {
        WalletLocalListFragment fragment = new WalletLocalListFragment();
        Bundle args = new Bundle();
        args.putBoolean("isVisible", isVisible);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            isVisible = getArguments().getBoolean("isVisible");
        }
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonFragmentComponent.builder()
                .appComponent(appComponent)
                .personFragmentModule(new PersonFragmentModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUi() {
        super.initUi();
        //getWallets();
        //isLocalWalletOpened = WalletStoreManger.getHdWallets() != null;
        //  isLocalWalletOpened = SPUtil.getBoolean(LibConstant.isLocalWalletOpened);
        refreshLayout.setEnableRefresh(isLocalWalletOpened);
        refreshLayout.setEnableLoadMore(false);
        //llList.setVisibility(isLocalWalletOpened ? View.VISIBLE : View.GONE);
        //llGuide.setVisibility(isLocalWalletOpened ? View.GONE : View.VISIBLE);
//        if (isLocalWalletOpened) {
//            getWallets();
//        }
        //getWallets();
        initRecyclerView();

    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        //adapter = new LocalWalletListAdapter(walletList);
        adapter = new LocalWalletListAdapter(hdwallets);
        rvList.setLayoutManager(layoutManager);
        rvList.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //loadData();
                getLocalWalletData(false);
            }
        });
        setVisibleView();
    }


    @Override
    protected void initData() {


    }

    private void setVisibleView() {
        tvAssetTotal.setText(isVisible ? "CNY " + totalAsset : "CNY ****");
        adapter.setShowAsset(isVisible);
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onFirstUserVisible() {
        /*if (!hdwallets.isEmpty()) {
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            getLocalWalletData(true);
        }*/
        isFistRequest = true;
        getWallets();
        setVisibleView();


    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        isFistRequest = false;
        getWallets();
        setVisibleView();
        /*if (!hdwallets.isEmpty()) {
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            getLocalWalletData(false);
        }*/
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_fragment_wallet_local_list;
    }


    @OnClick(R2.id.tv_create_wallet)
    void createWallet() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isCreatedWallet", true);
        mContext.startActivity(intent);
        // launch(SetPinCodeActivity.class);
    }


    @OnClick(R2.id.tv_import_wallet)
    void importWallet() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isImportWallet", true);
        mContext.startActivity(intent);
        //launch(RestoreHdWalletActivity.class);
    }


    private void getWallets() {

        mPresenter.getAllHdWalletCaches(null);


    }


    @OnClick(R2.id.iv_add_wallet)
    void selectCoin() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_LOCAl);
        intent.putExtra("isImportWallet", true);//如果是本地钱包则按钮为导入钱包
        mContext.startActivity(intent);
    }

    private void saveWallets() {
        for (HdWalletCache wallet : hdwallets) {
            mPresenter.addHdWalletCache(wallet);
        }
    }


    public String getTotalAsset() {
        return totalAsset;
    }

    private void setTotoalLocalAsset() {
        BigDecimal totalLocal = BigDecimal.ZERO;
        for (HdWalletCache wallet : hdwallets) {
            BigDecimal bd = new BigDecimal(wallet.getBanlanceCny());
            totalLocal = totalLocal.add(bd);
        }
        totalAsset = String.valueOf(totalLocal.setScale(2, RoundingMode.DOWN));
        setVisibleView();
    }

    //----------------------------------------------缓存获取钱包--------------------------------------
    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        hdwallets.clear();
        if (datas != null) {
            hdwallets.addAll(datas);
        }
        if (!hdwallets.isEmpty()) {
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            setTotoalLocalAsset();

            getLocalWalletData(isFistRequest);
            adapter.notifyDataSetChanged();
        } else {
            llList.setVisibility(View.GONE);
            llGuide.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {

    }


    //----------------------------------------------请求以太坊获取钱包数据----------------------------
    private void getLocalWalletData(boolean isFirst) {

        if (!hdwallets.isEmpty()) {
            for (HdWalletCache wallet : hdwallets) {
                if (wallet.getCoinType().equals(ETH)) {
                    mPresenter.getSingleEthBalance(wallet.getAddress(), isFirst);
                }
            }
        }

    }

    private void getUsdCnyRate() {
        mPresenter.getUsdCnyRate("usd", "cny");
    }

    private void getEthPrice() {
        mPresenter.getEthPrice();
    }


    @Override
    public void onGetSingleEthBalanceSuccess(String data, String addr) {
        refreshLayout.finishRefresh();
        for (HdWalletCache wallet : hdwallets) {
            if (wallet.getCoinType().equals(ETH) && wallet.getAddress().equals(addr)) {
                //此处以后余额 转账存数据库 进行单位换算 原本返回wei 换算成ether
                if (new BigDecimal(data).compareTo(BigDecimal.ZERO) == 0) {
                    wallet.setBalance("0");
                } else {
                    wallet.setBalance(new BigDecimal(data).divide(ExchangeCalculator.ONE_ETHER, 8, RoundingMode.DOWN) + "");
                }
            }
        }
        //saveWallets();
        adapter.notifyDataSetChanged();
        getUsdCnyRate();

    }

    @Override
    public void onGetSingleEthBalanceFailed() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void onGetUsdCnyRateSuccessed(String data) {
        ethRate = new BigDecimal(data);
        getEthPrice();
    }

    @Override
    public void onGetEthPriceSuccessed(String data) {
        EthPrice ethPrice = new Gson().fromJson(data, EthPrice.class);
        BigDecimal ethCny = new BigDecimal(ethPrice.getEthusd()).multiply(ethRate);
        BigDecimal totalLocal = BigDecimal.ZERO;

        for (HdWalletCache wallet : hdwallets) {
            if (wallet.getCoinType().equals(ETH)) {
                BigDecimal bd = new BigDecimal(wallet.getBalance()).multiply(ethCny);
                wallet.setBanlanceCny(bd.setScale(2, RoundingMode.DOWN) + "");
                totalLocal = totalLocal.add(bd);
            }
        }
        saveWallets();
        adapter.notifyDataSetChanged();
        //设置总额
        totalAsset = String.valueOf(totalLocal.setScale(2, RoundingMode.DOWN));
        setVisibleView();

        EventBus.getDefault().post(new BaseEvent<>(REFRESH_TOTAL_ASSET));

    }


    //----------------------------------------------event--------------------------------------------

    @Subscriber
    void onGetNewWallet(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.IS_GET_NEW_WALLET) {
            //刷新local 钱包列表 暂时只考虑eth
            getWallets();
            setVisibleView();
            llList.setVisibility(View.VISIBLE);
            llGuide.setVisibility(View.GONE);
            //连接以太坊 ，请求数据
            getLocalWalletData(true);
        }
    }


    @Subscriber
    void setAssetVisible(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.IS_ASSET_VISIBLE) {
            isVisible = (boolean) event.getData();
            setVisibleView();
        }
    }


}
